//  g++14 -O1 main.cpp maxCp.cpp Geometry.cpp

#include <iostream>
#include <iomanip>
#include <fstream>
#include "def.h"
#include "Geometry.hpp"
#include "functions.h"
#include <cmath>
using namespace std;

int main()
{
    string gridfile{"homework.dat"};
    Geometry metric{gridfile};
    Point check{0.0, 0.0, 0.0};
    metric.CalcuArea(check);

    constexpr double Ma{15.0};
    double cpMax = MaxCp(Ma);
    Point *area = metric.GetArea();

    // double cpx{}, cpy{}, cpz{};
    // 计算来流角并计算压强系数
    double alpha{30.0}, beta{45.0};
    alpha *= RAD;
    beta *= RAD;
    Point vn{-sin(beta), cos(beta) * sin(alpha), -cos(beta) * cos(alpha)};

    long numTria = metric.GetNumTria();
    double S, sin2, *cp{new double[numTria]};
    Point sn{}, val;
    for (long i = 0; i < numTria; ++i)
    {
        S = sqrt(area[i].x * area[i].x + area[i].y * area[i].y + area[i].z * area[i].z);
        sn.x = area[i].x / S;
        sn.y = area[i].y / S;
        sn.z = area[i].z / S;
        double tmp;
        tmp = sn.x * vn.x + sn.y * vn.y + sn.z * vn.z;
        cp[i] = (tmp < 0.0) ? cpMax * tmp * tmp : 0.0;
    }

    // 输出即可
    ofstream fout{"homework_result_a30_b45.dat"};
    fout << "TITLE   = \" cp value\" \n";
    fout << "VARIABLES = \"X\",\"Y\",\"z\",\"cp\" \n";
    fout << "ZONE T=\"Triangulation\""
         << "Nodes=" << metric.GetNumNode()
         << ", Elements=" << metric.GetNumTria()
         << ", ZONETYPE=FETriangle  DATAPACKING=BLOCK\n"
         << "VARLOCATION=([1-3]=NODAL, [4]=CELLCENTERED)\n";
    Point *coord = metric.GetCoordinate();
    Tria *tria = metric.GetTriangle();

    fout << scientific << setprecision(10);
    long numNode = metric.GetNumNode();
    // for (long i = 0; i < numNode; ++i)
    // {
    //     fout << coord[i].x << "\t" << coord[i].y
    //          << "\t" << coord[i].z << "\t" << //cp[i] << "\n";
    // }
    for (long i = 0; i < numNode; ++i)
        fout << coord[i].x << "\n";
    for (long i = 0; i < numNode; ++i)
        fout << coord[i].y << "\n";
    for (long i = 0; i < numNode; ++i)
        fout << coord[i].z << "\n";
    for (long i = 0; i < numTria; ++i)
        fout << cp[i] << "\n";
    for (long i = 0; i < numTria; ++i)
        fout << (tria[i].node[0] + 1) << "\t"
             << (tria[i].node[1] + 1) << "\t"
             << (tria[i].node[2] + 1) << "\n";
    fout.close();
    return 0;
}